package com.webdrider.servlet.util.parser.blog;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

import com.common.model.abstracts.AbstractRequest;
import com.common.model.abstracts.AbstractResponse;
import com.common.security.exceptions.HTTPException;
import com.common.security.exceptions.ParserException;
import com.webdrider.model.action.blog.Category;
import com.webdrider.model.action.blog.Post;
import com.webdrider.model.requests.blog.AddBlogPostRequest;
import com.webdrider.model.response.blog.AddBlogPostResponse;
import com.webdrider.servlet.abstracts.XMLParserBase;
import com.webdrider.servlet.util.HTTPProtocol;

public class AddBlogPostXMLParser extends XMLParserBase {

	@Override
	public AbstractRequest parseRequest(InputStream stream) throws HTTPException, ParserException {
		AddBlogPostRequest request = new AddBlogPostRequest();
		
		Document document = createDocument(stream);
		
		Node actionNode = getActionNode(document);
		Node contentNode = getContentNode(document);
		
		insertAction(actionNode, request);
		Element element = getContent(contentNode);
		
		Element session = getElement(element, HTTPProtocol.SESSION);
		Element post = getElement(element, HTTPProtocol.POST);
		List<Element> categories = getAllElements(post, HTTPProtocol.CATEGORY);
		
		Post blogPost = new Post();
		List<Category> postCategories = new ArrayList<Category>();
		Category category;
		
		for (int i = 0; i < categories.size(); i++) {
			category = new Category();
			category.setValue(categories.get(i).getAttribute(HTTPProtocol.ATTRIBUTE_VALUE));
			postCategories.add(category);
		}
		
		blogPost.setTitle(post.getAttribute(HTTPProtocol.ATTRIBUTE_TITLE));
		blogPost.setContent(post.getAttribute(HTTPProtocol.ATTRIBUTE_VALUE));
		blogPost.setCategories(postCategories);
		
		request.setSessionId(session.getAttribute(HTTPProtocol.ATTRIBUTE_VALUE));
		request.setPost(blogPost);
		
		return request;
	}

	@Override
	public String parseResponse(AbstractResponse abstractResponse) throws ParserException {
		AddBlogPostResponse response = null;
		
		if (abstractResponse instanceof AddBlogPostResponse) {
			response = (AddBlogPostResponse) abstractResponse;
		} else {
			throw new ParserException(ParserException.RESPONSE_MATCH_ERROR);
		}
		
		StringBuilder builder = new StringBuilder();
		
		builder.append(HTTPProtocol.RESPONSE_TAG);
		builder.append(HTTPProtocol.CLOSE_TAG);
		builder.append(HTTPProtocol.END_LINE);
		builder.append(getAction(response.getRequestAction()));
		builder.append(HTTPProtocol.CONTENT_TAG);
		builder.append(HTTPProtocol.END_LINE);
		builder.append(HTTPProtocol.CONTENT_END_TAG);
		builder.append(HTTPProtocol.END_LINE);
		builder.append(HTTPProtocol.RESPONSE_END_TAG);
		
		return builder.toString();
	}

}
